/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tetris_invader.personagens;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import tetris_invader.itens.Life_Item;
import tetris_invader.util.Fase;
import tetris_invader.util.Timer;
import tetris_invader.util.TimerListener;

/**
 * Classe responsavel apenas por fazer a explosao dos personagens. Em sua
 * maioria, os inimigos.
 */
public final class Explode implements TimerListener {

    private Point posicao;
    private Image[] img;
    private boolean flag;
    private int cont;
    private Player explosion;
    private Timer timer;

    public Explode() {
        timer = new Timer(this, 10);
        flag = true;
        img = capturaImagem();
        cont = 0;


        try {
            FileInputStream log;
            try {
                log = new FileInputStream("src/sound/explosion.mp3");
                explosion = new Player(log);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Life_Item.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (JavaLayerException ex) {
            Logger.getLogger(Life_Item.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Image[] capturaImagem() {
        Image[] imagem = new Image[8];
        for (int i = 0; i < imagem.length; i++) {
            String filename = "/images/explode/explode" + (i + 1) + ".png";
            URL url = Fabrica.class.getResource(filename);
            imagem[i] = Toolkit.getDefaultToolkit().getImage(url);
            imagem[i] = imagem[i].getScaledInstance(24, 16, 1);
        }
        return imagem;
    }

    public boolean isFlag() {
        return flag;
    }

    /**
     * Inverte o sentido da flag
     */
    public void setFlag() {
        this.flag = !this.flag;

    }

    public Point getPosicao() {
        return posicao;
    }

    public void setPosicao(Point posicao) {
        this.posicao = posicao;
    }
    private int delay = 0;

    public void desenha(Graphics2D g2, Fase fase) {
        g2.drawImage(img[cont], posicao.x, posicao.y, fase);
        if (delay > 0) {
            cont++;
            if (cont >= img.length) {
                setFlag();
            }
            delay = 0;
        } else {
            delay++;
        }
    }

    public void start() {
        timer.start();
    }

    public void update() {
        try {
            explosion.play();
        } catch (JavaLayerException ex) {
            Logger.getLogger(Explode.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void stop() {
        timer.pause();
    }
}
